<template>
	<div>
		<!-- 导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>权限管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片 -->
		<el-card>
			<!-- 添加角色 -->
			<el-row>
				<el-col>
					<el-button type="primary" @click="addRolesDialogVisible=true">添加角色</el-button>
					<el-dialog title="添加角色" :visible.sync="addRolesDialogVisible" 
					width="50%" @close="addRoleDialogClosed">
						<el-form :model="addRoleForm" :rules="addFormRole" ref="addRoleFormRef" label-width="120px">
							<el-form-item label="角色名称" prop="roleName">
								<el-input v-model="addRoleForm.roleName"></el-input>
							</el-form-item>
							<el-form-item label="角色描述" prop="roleDesc">
								<el-input v-model="addRoleForm.roleDesc"></el-input>
							</el-form-item>
						</el-form>
						<span slot="footer" class="dialog-footer">
							<!-- 隐藏对话框-->
							<el-button @click="addRolesDialogVisible = false">取 消</el-button>
							<el-button type="primary" @click="addRoles">确 定</el-button>
						</span>
					</el-dialog>
				</el-col>
			</el-row>
			<!-- 角色列表 -->
			<el-table :data="rolesList" border stripe>
				<el-table-column type="expand">
					<!-- 展开列 -->
					<template slot-scope="scope">
						<el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
							<!-- 渲染一级权限 -->
							<el-col :span="5">
								<el-tag closable="" @close="removeright(scope.row,item1.id)">{{item1.authName}}</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<!-- 渲染二级和三级权限 -->
							<el-col :span="19">
								<!-- 通过for循环渲染二级权限 -->
								<el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
									<el-col :span="6">
										<el-tag type="success" closable="" @close="removeright(scope.row,item2.id)">{{item2.authName}}</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
									<el-col :span="18">
										<el-tag v-for="(item3,i3) in item2.children" :key="item3.id" type="warning" closable @close="removeright(scope.row,item3.id)">{{item3.authName}}</el-tag>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
					</template>
				</el-table-column>
				<!-- 索引列 -->
				<el-table-column type="index" label="#"></el-table-column>
				<el-table-column prop="roleName" label="角色名称"></el-table-column>
				<el-table-column prop="roleDesc" label="角色描述"></el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<!-- 编辑 -->
						<el-button type="primary" icon="el-icon-edit" size="small" @click="showDialogClosed(scope.row.id)">编辑</el-button>
						
						<el-dialog title="编辑角色" :visible.sync="editRolesDialogVisible"
						width="50%">
							<el-form :model="editRoleForm" :rules="editFormRole" ref="editRoleFormRef" label-width="120px">
								<el-form-item label="角色名称" prop="roleName">
									<el-input v-model="editRoleForm.roleName"></el-input>
								</el-form-item>
								<el-form-item label="角色描述" prop="roleDesc">
									<el-input v-model="editRoleForm.roleDesc"></el-input>
								</el-form-item>
							</el-form>
							<span slot="footer" class="dialog-footer">
								<!-- 隐藏对话框-->
								<el-button @click="editRolesDialogVisible = false">取 消</el-button>
								<el-button type="primary" @click="editRoleInfo">确 定</el-button>
							</span>
						</el-dialog>
						
						<el-button type="danger" size="mini" icon="el-icon-delete" @click="delopen(scope.row.id)">删除</el-button>
						<el-button type="warning" size="mini" icon="el-icon-setting" @click="showRightsDialog(scope.row)">分配权限</el-button>
						<!-- 分配权限对话框 -->
						<el-dialog title="分配权限" :visible.sync="rightsdialogVisible" width="50%" @close="RightsDialogClosed">
							<!-- 树形控件 -->
							<el-tree :data="rightsList" :props="defaultProps" show-checkbox node-key="id" default-expand-all
							 :default-checked-keys="defKeys" ref="treeref">

							</el-tree>
							<!-- 底部区域-->
							<span slot="footer" class="dialog-footer">
								<!-- 隐藏对话框-->
								<el-button @click="rightsdialogVisible = false">取 消</el-button>
								<el-button type="primary" @click="allrights">确 定</el-button>
							</span>
						</el-dialog>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				//所有角色
				rolesList: [],
				//控制分配权限对话框的显示与隐藏
				rightsdialogVisible: false,
				//所有权限数据
				rightsList: [],
				//树形控件
				defaultProps: {
					label: 'authName',
					children: 'children'
				},
				//默认选中的节点
				defKeys: [],
				//当前即将分配权限角色的id
				roleid: '',
				//控制添加角色对话框的显示与隐藏
				addRolesDialogVisible: false,
				addRoleForm: {
					roleName: '',
					roleDesc: ''
				},
				addFormRole: {
					roleName: [{
							required: true,
							/* 必填项 */
							message: '请输入角色名称',
							/* 错误提示 */
							trigger: 'blur' /* 在失去鼠标焦点时触发 */
						},
						{
							min: 3,
							max: 8,
							message: '长度在 3 到 8 个字符',
							trigger: 'blur'
						}
					],
					roleDesc: [{
							required: true,
							/* 必填项 */
							message: '请输入角色描述',
							/* 错误提示 */
							trigger: 'blur' /* 在失去鼠标焦点时触发 */
						},
						{
							min: 3,
							max: 10,
							message: '长度在 3 到 10 个字符',
							trigger: 'blur'
						}
					]
				},
				//控制添加角色对话框的显示与隐藏
				editRolesDialogVisible:false,
				editRoleForm: {},
				editFormRole: {
					roleName: [{
							required: true,
							/* 必填项 */
							message: '请输入角色名称',
							/* 错误提示 */
							trigger: 'blur' /* 在失去鼠标焦点时触发 */
						},
						{
							min: 3,
							max: 8,
							message: '长度在 3 到 8 个字符',
							trigger: 'blur'
						}
					],
					roleDesc: [{
							required: true,
							/* 必填项 */
							message: '请输入角色描述',
							/* 错误提示 */
							trigger: 'blur' /* 在失去鼠标焦点时触发 */
						},
						{
							min: 3,
							max: 10,
							message: '长度在 3 到 10 个字符',
							trigger: 'blur'
						}
					]
				},
				
			}
		},
		created() {
			this.getRolesList()
		},
		methods: {
			async getRolesList() {
				const {
					data: res
				} = await this.$http.get('roles')
				if (res.meta.status !== 200) {
					return this.$message.error('获取权限列表失败')
				}
				this.rolesList = res.data
				console.log(this.rolesList)
			},
			async removeright(role, rightsid) {
				const removeresult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '删除提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				//如果用户确认删除，返回字符串confirm
				//如果用户取消删除，返回字符串cancel
				/* console.log(removeresult) */
				if (removeresult !== 'confirm') {
					return this.$message.info('已经取消删除！')
				}
				/* console.log('确认删除') */
				const {
					data: res
				} = await this.$http.delete(`roles/${role.id}/rights/${rightsid}`)
				if (res.meta.status !== 200) {
					this.$message.error('删除权限失败!')
				}
				this.$message.success('修改权限成功!')
				//重新获取用户列表
				role.children = res.data
				/* this.getRolesList() */
			},
			//展示分配权限的对话框
			async showRightsDialog(role) {
				this.roleid = role.id
				//获取所有权限的数据
				const {
					data: res
				} = await this.$http.get('rights/tree')
				if (res.meta.status !== 200) {
					return this.$message.error('查询权限信息失败！')
				}
				//把获取到的权限数据保存到data中
				this.rightsList = res.data
				console.log(this.rightsList)
				//获取三级节点的id
				this.getLeafKeys(role,
					this.defKeys)

				this.rightsdialogVisible = true
			},
			getLeafKeys(node, arr) {
				//如果当前node节点不包含children属性，则是三级节点
				if (!node.children) {
					return arr.push(node.id)
				}
				node.children.forEach(item =>
					this.getLeafKeys(item, arr))
			},
			//监听分配对话框的关闭
			RightsDialogClosed() {
				this.defKeys = []
			},
			//展示编辑对话框
			async showDialogClosed(id) {
				//获取修改id
				/* console.log(id) */
				const {
					data: res
				} = await this.$http.get('roles/' + id)
				if (res.meta.status !== 200) {
					return this.$message.error('查询用户信息失败！')
				}
				this.editRoleForm = res.data
				this.editRolesDialogVisible = true
			},
			//编辑
			editRoleInfo() {
				this.$refs.editRoleFormRef.validate(async vail => {
					console.log(vail)
					if (!vail) return
					//发起请求
					const {
						data: res
					} = await this.$http.
					put('roles/' + this.editRoleForm.roleId, {
						roleName: this.editRoleForm.roleName,
						roleDesc: this.editRoleForm.roleDesc
					})
					console.log(this.editRoleForm.roleId)
					console.log(res.meta)
					if (res.meta.status !== 200) {
						this.$message.error('修改用户失败!')
					}
					//隐藏添加用户对话框
					this.editRolesDialogVisible = false
					//重新获取用户列表
					this.getRolesList()
					this.$message.success('修改用户成功!')
				})
			},
			//删除
			async delopen(id) {
				/* 弹框询问是否删除 */
				const delresult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '删除提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				//如果用户确认删除，返回字符串confirm
				//如果用户取消删除，返回字符串cancel
				/* console.log(delresult) */
				if (delresult !== 'confirm') {
					return this.$message.info('已经取消删除！')
				}
				/* console.log('确认删除') */
				const {
					data: res
				} = await this.$http.delete('roles/' + id)
				if (res.meta.status !== 200) {
					this.$message.error('删除用户失败!')
				}
				this.$message.success('修改用户成功!')
				//重新获取用户列表
				this.getRolesList()
			},
			//为角色分配权限
			async allrights() {
				const keys = [
					...this.$refs.treeref.getCheckedKeys(),
					...this.$refs.treeref.getHalfCheckedKeys()
				]
				const idStr = keys.join(',')
				const {
					data: res
				} = await this.$http.post(`roles/${this.roleid}/rights`, {
					rids: idStr
				})
				if (res.meta.status !== 200) {
					return this.$message.error('更新权限信息失败！')
				}
				this.$message.success('更新权限信息成功！')
				/* 刷新权限列表 */
				this.getRolesList()
				/* 关闭 */
				this.rightsdialogVisible = false
			},
			//重置信息
			addRoleDialogClosed() {
				this.$refs.addRoleFormRef.resetFields()
			},
			//点击按钮，添加新角色		
			addRoles() {
				this.$refs.addRoleFormRef.validate(async vail => {
					if (!vail) return
					//发起添加用户的网络请求
					const {
						data: res
					} = await this.$http.post('roles', this.addRoleForm)
					if (res.meta.status !== 201) {
						this.$message.error('添加角色失败!')
					}
					this.$message.success('添加角色成功!')
					//隐藏添加用户对话框
					this.addRolesDialogVisible = false
					//重新获取用户列表
					this.getRolesList()
				})
			}			
		}
	}
</script>

<style lang="less" scoped>
	.el-tag {
		margin: 7px;
	}

	.bdtop {
		border-top: 1px solid #eee;
	}

	.bdbottom {
		border-bottom: 1px solid #eee;
	}

	.vcenter {
		display: flex;
		align-items: center;
	}
</style>
